package org.example.chapter8.server.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.example.chapter8.protocol.request.MessageRequestPacket;
import org.example.chapter8.protocol.response.MessageResponsePacket;
import org.example.chapter8.session.Session;
import org.example.chapter8.utils.SessionUtil;

public class MessageRequestHandler extends SimpleChannelInboundHandler<MessageRequestPacket> {

    public static final MessageRequestHandler INSTANCE = new MessageRequestHandler();

    private MessageRequestHandler() {

    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageRequestPacket msg) throws Exception {
        long begin = System.currentTimeMillis();

        Session session = SessionUtil.getSession(ctx.channel());

        MessageResponsePacket messageResponsePacket = new MessageResponsePacket();
        messageResponsePacket.setFromUserId(session.getUserId());
        messageResponsePacket.setFromUsername(session.getUsername());
        messageResponsePacket.setMessage(msg.getMessage());

        Channel channel = SessionUtil.getChannel(msg.getToUserId());
        if (channel != null && SessionUtil.hasLogin(channel)) {
            channel.writeAndFlush(messageResponsePacket).addListener(future -> {
                if (future.isDone()) {

                }
            });
        } else {
            System.err.println("[" + session.getUserId() + "] 不在线，发送失败！");
        }
    }
}
